<template>
	<uni-popup class="pop" ref="popupRef" type="bottom" :animation="true">
		<view class="pop-content" :style="{ marginBottom: '-' + safeBottom + 'px'}">
			<view class="header">
				<view>
				</view>
				<text>套餐说明</text>
				<image @click="closePop"
					src="https://img.js.design/assets/img/66eabe069abe61d89118f24e.png#ccfd6fdbad4e05399710f7a1a0b16e9b"
					mode=""></image>
			</view>
			<view class="type-card">
				<scroll-view class="viewScroll" :scroll-x="true" scroll-y="false">
					<view class="scroll-box">
						<view class="card" :class="[active === item.type_number ? 'active' : '']"
							v-for="(item,index) in packageCardInfo" :key="item.type_number"
							@click="clickType(item.type_number,item)">
							{{item.type_name}}
							<text>{{item.type_number}}人{{item.type_title}}团，一价全包</text>
						</view>
					</view>
				</scroll-view>
			</view>
			<view class="container">
				<view class="calendar-wrapper">
					<view class="date-header">
						<view class="top">
							出行日期
						</view>
						<view class="bottom">
							<view>{{y + '年' + formatNum(m) + '月' }}</view>
							<view class="imagebox">
								<view class="preWidth" @click="changeMonth('pre')">
									<view class="pre">
										<image src="/static/product-cwr/left-icon.png" mode="" class="pre-img"></image>
									</view>
								</view>
								<view class="nextWidth" @click="changeMonth('next')">
									<view class="next">
										<image src="/static/product-cwr/right-icon.png" mode="" class="next-img">
										</image>
									</view>
								</view>
							</view>
						</view>

					</view>
					<view class="week">
						<view class="week-day" v-for="(item, index) in weekDay" :key="index">{{ item }}</view>
					</view>
					<view class="content" :style="{ height: height }">
						<view :style="{ top: positionTop + 'rpx' }" class="days">
							<view class="item" v-for="(item, index) in dates" :key="index">
								<view class="day" @click="selectOne(item, $event)" :class="{
								choose: choose === `${item.year}-${item.month}-${item.date}` && item.isCurM,
								nolm: !item.isCurM,
								past: isPast(item.year, item.month, item.date),
								noTicket: !hasTicket(item.year, item.month, item.date),
								hidden: !item.isCurM
							}">
									<text v-if="hasTicket(item.year, item.month, item.date)">
										余{{ getTicketInfo(item.year, item.month, item.date)?.num || '' }}
									</text>
									<text class="time">{{ Number(item.date) }}</text>
									<text v-if="hasTicket(item.year, item.month, item.date)">
										{{ getTicketInfo(item.year, item.month, item.date)?.price }}元
									</text>
								</view>
							</view>
						</view>

					</view>
				</view>
			</view>
			<view class="footer">
				<view class="time-tips" v-if="choose && active_days">
					{{ formattedStartDate }}出发 - {{ formattedEndDate }}返程
				</view>
				<view class="button" @click="nextSele">
					下一步
				</view>
			</view>
		</view>
	</uni-popup>
</template>

<script setup>
	import moment from 'moment';
	import {
		ref,
		computed,
		watch
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		safeBottom
	} from '@/config/systemInfo.js'
	const months = ref([]);
	const popupRef = ref(null);
	const data = ref([1, 2, 3])
	const active = ref(1)
	// Props
	const props = defineProps({
		weekstart: {
			type: Number,
			default: 1
		},
		markDays: {
			type: Array,
			default: () => []
		},

		disabledAfter: {
			type: Boolean,
			default: false
		},
		packageCardInfo: {
			type: Array,
			default: () => []
		},
		ticketInfo: {
			type: Array,
			default: () => []
		},
		dayId: {
			type: Number,
			default: 0
		},
		type_number: {
			type: String,
			default: ''
		},
		active_days: {
			type: Number,
			default: null
		}
	});
	// Data
	const weektext = ['日', '一', '二', '三', '四', '五', '六'];
	const y = ref(new Date().getFullYear()); // 年
	const m = ref(new Date().getMonth() + 1); // 月
	const dates = ref([]); // 当前月的日期数据
	const positionTop = ref(0);
	const monthOpen = ref(true);
	const choose = ref('');
	const nowtime = ref('');
	watch(() => props.type_number, (newValue) => {
		console.log('newNumber===>', newValue);
		if (newValue) {
			choose.value = ''
		}
	});
	// 暴露方法给父组件

	const exposeMethods = {
		showPopup: (typeNumber) => {
			popupRef.value.open();
			console.log('typeNumber', typeNumber);
			active.value = typeNumber
			getnowtime();
			dates.value = monthDay(y.value, m.value);

		},
		closePopup: () => {
			popupRef.value.close();
		}
	};
	// 返回months以便在模板中使用
	defineExpose({
		...exposeMethods
	});

	// 计算选择日期的开始和结束时间
	const formattedStartDate = computed(() => {
		if (!choose.value) return ''; // 如果没有选择日期，返回空字符串
		const startDate = moment(choose.value); // 使用moment来格式化日期
		return startDate.format('YYYY.M.D'); // 格式化为 "2024年6月17日"
	});

	const formattedEndDate = computed(() => {
		if (!choose.value || !props.active_days) return ''; // 如果没有选择日期或旅游天数为0，返回空字符串
		const endDate = moment(choose.value).add(props.active_days - 1, 'days'); // 计算结束日期
		return endDate.format('YYYY.M.D'); // 格式化为 "2024年6月19日"
	});


	// Computed properties
	const weekDay = computed(() => {
		return weektext.slice(props.weekstart).concat(weektext.slice(0, props.weekstart));
	});
	const height = computed(() => {
		return (dates.value.length / 7) * 110 + 'rpx';
	});
	// Methods
	const formatNum = num => {
		let res = Number(num);
		return res < 10 ? '0' + res : res;
	};

	const getToday = () => {
		let date = new Date();
		let y = date.getFullYear();
		let m = date.getMonth();
		let d = date.getDate();
		let today = {
			date: `${y}-${formatNum(m + 1)}-${formatNum(d)}`
		};
		return today;
	};
	const getnowtime = () => {
		let date = new Date();
		let y = date.getFullYear();
		let m = date.getMonth();
		let d = date.getDate();
		nowtime.value = `${y}-${formatNum(m + 1)}-${formatNum(d)}`;
	};
	const cachedDates = {};
	const lastMonth = ref(`${y.value}-${formatNum(m.value)}`);

	const monthDay = (y, month) => {
		let cacheKey = `${y}-${formatNum(month)}`;
		if (cachedDates[cacheKey]) {
			return cachedDates[cacheKey];
		}

		let dates = generateDates(y, month);
		cachedDates[cacheKey] = dates;
		return dates;
	};
	const generateDates = (y, month) => {
		let dates = [];
		let m = Number(month);
		let firstDayOfMonth = new Date(y, m - 1, 1).getDay(); // 当月第一天星期几
		let lastDateOfMonth = new Date(y, m, 0).getDate(); // 当月最后一天
		let lastDayOfLastMonth = new Date(y, m - 1, 0).getDate(); // 上一月的最后一天
		let startDay = (() => {
			if (firstDayOfMonth === props.weekstart) {
				return 0;
			} else if (firstDayOfMonth > props.weekstart) {
				return firstDayOfMonth - props.weekstart;
			} else {
				return 7 - props.weekstart + firstDayOfMonth;
			}
		})();
		let endDay = 7 - ((startDay + lastDateOfMonth) % 7);

		for (let i = 1; i <= startDay; i++) {
			dates.push({
				date: formatNum(lastDayOfLastMonth - startDay + i),
				day: props.weekstart + i - 1 || 7,
				month: m - 1 >= 0 ? formatNum(m - 1) : 12,
				year: m - 1 >= 0 ? y : y - 1
			});
		}
		for (let j = 1; j <= lastDateOfMonth; j++) {
			dates.push({
				date: formatNum(j),
				day: (j % 7) + firstDayOfMonth - 1 || 7,
				month: formatNum(m),
				year: y,
				isCurM: true
			});
		}
		for (let k = 1; k <= endDay; k++) {
			dates.push({
				date: formatNum(k),
				day: (lastDateOfMonth + startDay + props.weekstart + k - 1) % 7 || 7,
				month: m + 1 <= 12 ? formatNum(m + 1) : 1,
				year: m + 1 <= 12 ? y : y + 1
			});
		}
		return dates;
	};
	const isFutureDay = (y, m, d) => {
		let ymd = `${y}/${m}/${d}`;
		let formatDY = new Date(ymd.replace(/-/g, '/'));
		let showTime = formatDY.getTime();
		let curTime = new Date().getTime();
		return showTime > curTime;
	};

	const isToday = (y, m, d) => {
		let checkD = `${y}-${m}-${d}`;
		let today = getToday().date;
		return checkD === today;
	};
	const isPast = (y, m, d) => {
		let checkD = `${y}-${m}-${d}`;
		let today = getToday().date;
		return checkD < today;
	};
	// 新增computed属性用于转换ticketInfo数据结构
	const adaptedTicketInfo = computed(() => {
		return props.ticketInfo.map(item => {
			let timestamp = new Date(item.today).getTime();
			return {
				[timestamp.toString()]: [{
						num: item.count
					},
					{
						price: item.cost_final
					},
					{
						shop_cost_id: item.shop_cost_id
					},
					{
						shop_data_id: item.shop_data_id
					}
				]
			};
		});
	});
	// const getTicketInfo = (y, m, d) => {
	// 	let dateStr = `${y}-${formatNum(m)}-${formatNum(d)}`;
	// 	let timestamp = new Date(dateStr).getTime();
	// 	let ticketData = adaptedTicketInfo.value.find(info => Object.keys(info)[0] == timestamp.toString());
	// 	if (ticketData) {
	// 		let key = Object.keys(ticketData)[0];
	// 		let ticketInfo = ticketData[key];
	// 		return {
	// 			num: ticketInfo[0].num,
	// 			price: ticketInfo[1].price
	// 		};
	// 	}
	// 	return null;
	// };
	const getTicketInfo = (y, m, d) => {
		let dateStr = `${y}-${formatNum(m)}-${formatNum(d)}`;
		let timestamp = new Date(dateStr).getTime();
		let ticketData = adaptedTicketInfo.value.find(info => Object.keys(info)[0] == timestamp.toString());
		if (ticketData) {
			let key = Object.keys(ticketData)[0];
			let ticketInfo = ticketData[key];
			const num = ticketInfo[0].num;
			const price = ticketInfo[1].price;

			// 如果票数为空或为负数，返回 null
			if (num === null || num === undefined || num < 0) {
				return null;
			}

			return {
				num: num,
				price: price
			};
		}
		return null;
	};
	// const hasTicket = (y, m, d) => {
	// 	let dateStr = `${y}-${formatNum(m)}-${formatNum(d)}`;
	// 	let timestamp = new Date(dateStr).getTime();
	// 	return adaptedTicketInfo.value.some(info => Object.keys(info)[0] == timestamp.toString());
	// };
	const hasTicket = (y, m, d) => {
		let dateStr = `${y}-${formatNum(m)}-${formatNum(d)}`;
		let timestamp = new Date(dateStr).getTime();
		let ticketData = adaptedTicketInfo.value.find(info => Object.keys(info)[0] == timestamp.toString());
		if (ticketData) {
			let key = Object.keys(ticketData)[0];
			let ticketInfo = ticketData[key];
			const num = ticketInfo[0].num;

			// 如果票数为空或为负数，返回 false
			if (num === null || num === undefined || num <= 0) {
				return false;
			}

			return true;
		}
		return false;
	};
	// const selectOne = (i, event) => {
	// 	let date = `${i.year}-${i.month}-${i.date}`;
	// 	let selectD = new Date(date).getTime();
	// 	let curTime = new Date().getTime();
	// 	let week = new Date(date).getDay();
	// 	let weekText = ['日', '一', '二', '三', '四', '五', '六'];
	// 	let formatWeek = '星期' + weekText[week];
	// 	let response = {
	// 		date: date,
	// 		week: formatWeek
	// 	};

	// 	// 获取当前选择日期对应的day_id
	// 	let ticketData = adaptedTicketInfo.value.find(info => Object.keys(info)[0] == selectD.toString());
	// 	if (ticketData) {
	// 		let key = Object.keys(ticketData)[0];
	// 		let ticketInfo = ticketData[key];
	// 		console.log('ticketInfo', ticketInfo);
	// 		response.shop_cost_id = ticketInfo[2].shop_cost_id;
	// 		response.count = ticketInfo[0].num
	// 		response.shop_data_id = ticketInfo[3].shop_data_id

	// 	}

	// 	if (isPast(i.year, i.month, i.date) || !hasTicket(i.year, i.month, i.date)) {
	// 		console.log('过去的日子或没有票的日子不可选');
	// 		return; // 不允许选择过去的日期或没有票的日期
	// 	}
	// 	choose.value = date;
	// 	emits('selectOne', response)
	// };
	const selectOne = (i, event) => {
		let date = `${i.year}-${i.month}-${i.date}`;
		let selectD = new Date(date).getTime();
		let curTime = new Date().getTime();
		let week = new Date(date).getDay();
		let weekText = ['日', '一', '二', '三', '四', '五', '六'];
		let formatWeek = '星期' + weekText[week];
		let response = {
			date: date,
			week: formatWeek
		};

		// 获取当前选择日期对应的票数信息
		let ticketData = adaptedTicketInfo.value.find(info => Object.keys(info)[0] == selectD.toString());
		if (ticketData) {
			let key = Object.keys(ticketData)[0];
			let ticketInfo = ticketData[key];
			const num = ticketInfo[0].num;

			// 如果票数为空或为负数，不允许选择
			if (num === null || num === undefined || num < 0) {
				console.log('票数为空或为负数，不可选');
				return;
			}

			response.shop_cost_id = ticketInfo[2].shop_cost_id;
			response.count = ticketInfo[0].num;
			response.shop_data_id = ticketInfo[3].shop_data_id;
		}

		if (isPast(i.year, i.month, i.date) || !hasTicket(i.year, i.month, i.date)) {
			console.log('过去的日子或没有票的日子不可选');
			return; // 不允许选择过去的日期或没有票的日期
		}
		choose.value = date;
		emits('selectOne', response);
	};

	//下一步
	const nextSele = () => {
		if (choose.value) {
			popupRef.value.close();
			// 传递日期信息给父组件
			const startDate = formattedStartDate.value;
			const endDate = formattedEndDate.value;
			emits('nextSele',
				startDate,
				endDate,
				choose.value
			);
		}
	};

	const changeMonth = (type) => {
		if (type === 'pre') {
			if (m.value === 1) {
				m.value = 12;
				y.value -= 1;
			} else {
				m.value -= 1;
			}
		} else {
			if (m.value === 12) {
				m.value = 1;
				y.value += 1;
			} else {
				m.value += 1;
			}
		}
		let currentMonthKey = `${y.value}-${formatNum(m.value)}`;
		if (currentMonthKey !== lastMonth.value) {
			lastMonth.value = currentMonthKey;
			dates.value = monthDay(y.value, m.value);
		}
	};

	const closePop = () => {
		popupRef.value.close();
	}
	const clickType = (index, item) => {
		active.value = index
		emits('clickType', item, active.value)
		choose.value = ''
	}
	// Lifecycle hooks
	onLoad(() => {
		// choose.value = getToday().date;
		getnowtime();
		dates.value = monthDay(y.value, m.value);
		// 自动选中最近有票的日期
		const firstAvailableDate = findFirstAvailableDate();
		console.log('firstAvailableDate', firstAvailableDate);
		if (firstAvailableDate) {
			choose.value = firstAvailableDate; // 设置选中日期
		}
	});
	const findFirstAvailableDate = () => {
		for (let i = 0; i < dates.value.length; i++) {
			const item = dates.value[i];
			if (hasTicket(item.year, item.month, item.date)) {
				return `${item.year}-${item.month}-${item.date}`; // 返回最近有票的日期
			}
		}
		return null; // 如果没有票，返回null
	};


	// Emit
	const emits = defineEmits(['selectOne', 'nextSele', 'clickType']);
</script>

<style scoped>
	.pop-content {
		font-family: "仓耳渔阳体 W05";
		background: #f5f6f7;
		border-radius: 16rpx 16rpx 0rpx 0rpx;
	}

	.header {
		border-radius: 16rpx 16rpx 0rpx 0rpx;
		height: 43rpx;
		background: rgba(255, 255, 255, 1);
		padding: 24rpx 10rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 30rpx;
	}

	.header image {
		width: 44rpx;
		height: 44rpx;
	}

	.header text {
		font-size: 32rpx;
		font-weight: 400;
		color: rgba(51, 51, 51, 1);
	}

	.header>view {
		width: 44rpx;
	}

	.viewScroll {
		padding: 20rpx 20rpx;
		width: 748rpx;
		box-sizing: border-box;
	}

	.type-card {}

	.scroll-box {
		width: 100%;
		white-space: nowrap;
		overflow-x: auto;
		padding-bottom: 20rpx;
	}

	.card {
		display: inline-flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		margin-right: 30rpx;
		width: 370rpx;
		height: 130rpx;
		background-color: #fff;
		box-sizing: border-box;
		white-space: pre-line;
		gap: 4rpx;
		/* line-height: 130rpx; */
	}

	.card {
		font-size: 30rpx;
	}

	.card text {
		font-size: 18rpx;
		color: rgba(128, 128, 128, 1);
	}

	.active {
		border: 2rpx solid #000000;

	}

	.footer {
		display: flex;
		flex-direction: column;
		width: 100%;
		background-color: #fff;
		padding: 10rpx 16rpx;
		box-sizing: border-box;
		justify-content: center;
		align-items: center;
		gap: 20rpx;
	}

	.footer .time-tips {
		font-size: 20rpx;
		color: rgba(166, 166, 166, 1);
	}

	.footer .button {
		color: #fff;
		width: 90%;
		margin: 0 auto;
		background: rgba(54, 48, 48, 1);
		box-shadow: 0rpx 4rpx 8rpx rgba(0, 0, 0, 0.25);
		text-align: center;
		border-radius: 56rpx;
		padding: 20rpx 0;
	}

	.calendar-wrapper {
		font-family: "仓耳渔阳体 W05";
		color: #000;
		width: 100%;
		background-color: #fff;
		text-align: center;
		padding-bottom: 10rpx;
		padding: 0 10rpx;
		box-sizing: border-box;
	}

	.date-header {
		display: flex;
		align-items: center;
		flex-direction: column;
		gap: 4rpx;
		font-size: 38rpx;
		font-weight: bold;
		padding: 36rpx 16rpx;
	}

	.imagebox {
		display: flex;
		align-items: center;
		gap: 80rpx;
	}

	.date-header image {
		width: 20rpx;
		height: 23rpx;
	}

	.top {
		width: 100%;
		text-align: left;

	}

	.bottom {
		width: 100%;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 10rpx;
		box-sizing: border-box;
		font-size: 24rpx;
	}



	.week {
		display: flex;
		align-items: center;
		height: 80rpx;
		line-height: 80rpx;
		color: rgba(21, 11, 71, 1);
		font-size: 26rpx;
	}

	.week view {
		flex: 1;
	}

	.content {
		position: relative;
		overflow: hidden;
		transition: height 0.4s ease;
	}

	.days {
		transition: top 0.3s;
		display: flex;
		align-items: center;
		flex-wrap: wrap;
		position: relative;
	}

	.item {
		position: relative;
		display: block;
		width: calc(100% / 7);
	}

	.day {
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		font-size: 40rpx;
		overflow: hidden;
		border-radius: 16rpx;
		color: rgba(21, 11, 71, 0.8);
		padding: 14rpx 0;
	}

	.day text {
		font-size: 16rpx;
	}

	.day .time {
		font-size: 32rpx;
	}

	/* 点击选择的日期 */
	.choose {
		/* background-color: #fe7379; */
		color: #fff;
		background: rgba(38, 38, 38, 1);
		border-radius: 7.62rpx 7.62rpx, 7.62rpx, 7.62rpx;
		box-shadow: 0rpx 17rpx 51rpx rgba(233, 239, 245, 1);
	}

	.nolm {
		opacity: 0.5;
	}

	.past,
	.noTicket {
		opacity: 0.5;
	}

	.hidden {
		display: none;
	}

	.notSigned {
		font-style: normal;
		width: 8rpx;
		height: 8rpx;
		background: #fa7268;
		border-radius: 10rpx;
		position: absolute;
		left: 50%;
		bottom: 0;
		pointer-events: none;
	}

	.nextWidth {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.preWidth {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.today {
		color: #fff;
		background: linear-gradient(180deg, #08CC4E 0%, #02A53C 100%);
	}

	.workDay {
		font-style: normal;
		width: 8rpx;
		height: 8rpx;
		background: #4d7df9;
		border-radius: 10rpx;
		position: absolute;
		left: 50%;
		bottom: 0;
		pointer-events: none;
	}

	.markDay {
		font-style: normal;
		width: 8rpx;
		height: 8rpx;
		background: #fc7a64;
		border-radius: 10rpx;
		position: absolute;
		left: 50%;
		bottom: -20rpx;
		pointer-events: none;
	}

	.hide {
		height: 80rpx !important;
	}

	.dropDown {
		width: 50rpx;
		height: 50rpx;
		background-color: #fc7a64;
	}

	.weektoggle {
		height: 30rpx;
		position: relative;
		bottom: -10rpx;
		margin: 0 auto;
		background-color: #ffffff;
		padding: 38rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.drop {
		display: flex;
		align-items: center;
	}

	.weektoggle image {
		width: 28rpx;
		height: 28rpx;
		margin-right: 12rpx;
	}

	.drop-text {
		font-weight: 400;
		color: #02A53C;
		font-size: 24rpx;
	}

	.timer-head {
		position: relative;
	}

	.timer-head-img {
		height: 132rpx;
		width: 100%;
	}

	.timer-head-img image {
		width: 100%;
		height: 100%;
	}

	.nowtime {
		position: absolute;
		left: 26rpx;
		top: 66rpx;
		font-weight: 500;
		font-size: 32rpx;
		bottom: 28rpx;
	}
</style>